package com.ningkang.gateway.filters;

import com.ningkang.common.constants.JwtConstants;
import com.ningkang.common.constants.TokenConstants;
import com.ningkang.common.utils.JwtUtils;
import com.ningkang.common.utils.StringUtils;
import com.ningkang.gateway.config.IgnoreWhiteConfig;
import com.ningkang.gateway.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author：LeiHao
 * @Package：com.lh.gateway.filters
 * @name：AuthFilters
 * @Date：2024/8/12 09:00
 */
@Component
public class AuthFilters implements GlobalFilter, Ordered {

    @Autowired
    private IgnoreWhiteConfig ignoreWhiteConfig;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        List<String> whites = ignoreWhiteConfig.getWhites();
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (StringUtils.matches(path,whites)){
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)){
            return GatewayUtils.errorResponse(exchange,"token不能未空");
        }

        try {
            JwtUtils.parseToken(token);
        }catch (Exception e){
            return GatewayUtils.errorResponse(exchange,"token不合法");
        }

        String userKey = JwtUtils.getUserKey(token);
        if (!redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY+userKey)){
            return GatewayUtils.errorResponse(exchange,"token过期");
        }else {
            redisTemplate.expire(TokenConstants.LOGIN_TOKEN_KEY,15,TimeUnit.MINUTES);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
